/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package syslivros;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;


/**
 *
 * @author Rafael
 */
public class ReceberApostila extends javax.swing.JFrame {

    /**
     * Creates new form Excluir
     */
    public ReceberApostila() throws SQLException {
        
        initComponents();
        try {
                Conexao.conectar("root", "positivo");
                System.out.println("conetado!ура товарищи!");
                
            } catch (Exception ex) {
               JOptionPane.showMessageDialog(null,"Erro ao conectar ao banco"+ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
            } 
           
        try {
            PopulaComboCursos();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this,
                    "Erro ao carregar cursos" + ex.getMessage(), "ERRO", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void PopulaComboCursos() throws SQLException {
        String SQL = "select NomeCurso  from listacursos  ";
        ResultSet rs = Conexao.ConexaoJDBC.createStatement().executeQuery(SQL);
        DefaultComboBoxModel model = (DefaultComboBoxModel) cbApostila.getModel();
        model.removeAllElements();
        while (rs.next()) {
            model.addElement(rs.getString("NomeCurso"));
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnVoltar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        lblApostila = new javax.swing.JLabel();
        cbApostila = new javax.swing.JComboBox();
        lblDataEntrada = new javax.swing.JLabel();
        txtDataEntrada = new javax.swing.JFormattedTextField();
        lblQuantidade = new javax.swing.JLabel();
        txtQuantidade = new javax.swing.JTextField();
        btnAdicionar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Recebimento de Apostila");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        btnVoltar.setText("Voltar");
        btnVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVoltarActionPerformed(evt);
            }
        });
        btnVoltar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnVoltarKeyPressed(evt);
            }
        });

        lblApostila.setText("Apostila: ");

        cbApostila.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione uma Apostila", ".NET Framework", "Java", "Linux ", "Windows Server" }));

        lblDataEntrada.setText("Data de entrada: ");

        try {
            txtDataEntrada.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        lblQuantidade.setText("Quantidade: ");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblApostila)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbApostila, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblDataEntrada)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDataEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblQuantidade)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblApostila)
                    .addComponent(cbApostila, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblQuantidade)
                    .addComponent(txtQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDataEntrada)
                    .addComponent(txtDataEntrada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        btnAdicionar.setText("Adicionar");
        btnAdicionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdicionarActionPerformed(evt);
            }
        });
        btnAdicionar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnAdicionarKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnAdicionar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnVoltar)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(92, 92, 92)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(153, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 146, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnVoltar)
                    .addComponent(btnAdicionar))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-464)/2, (screenSize.height-338)/2, 464, 338);
    }// </editor-fold>//GEN-END:initComponents

    private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVoltarActionPerformed
        new Apostilas().setVisible(true);
        this.dispose();
    }//GEN-LAST:event_btnVoltarActionPerformed

    private void btnVoltarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnVoltarKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            btnVoltarActionPerformed(null);
        }
    }//GEN-LAST:event_btnVoltarKeyPressed

    private void btnAdicionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicionarActionPerformed
        if ((!txtQuantidade.getText().equals("")) && (!txtQuantidade.getText().equals("0")) && (!txtDataEntrada.getText().equals("  /  /    "))) {
            String curso = (String) cbApostila.getSelectedItem();
             String data=txtDataEntrada.getText();
            int qtdApostila = 0;
            int qtApostilas_Atual=0;
            try{qtdApostila=Integer.valueOf(txtQuantidade.getText());}catch(Exception ex1){
            JOptionPane.showMessageDialog(this, "Digite apenas numeros inteiros"+ex1.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
            }
           int qtApostilasUpdate;
    
            switch (curso) {
                case ".NET":
                    try {
                       PreparedStatement p = Conexao.ConexaoJDBC.prepareStatement( "select * from estoque_base  where qt_Dotnet >=0 " );
                       ResultSet rs=p.executeQuery();
        while(rs.next()){
            
           qtApostilas_Atual =rs.getInt("qt_Dotnet");
            
       
        }qtApostilasUpdate=qtdApostila+qtApostilas_Atual;
          if(JOptionPane.showConfirmDialog(this, "Verifique os dados antes de confirmar: \n"
                + "Apostila: "+curso+"\n"
               
                +"Quantidade: "+qtdApostila+"\n"
                +"Data de Envio: "+data+"\n"
               
               ,"Confirmação",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                        PreparedStatement ps = Conexao.ConexaoJDBC.prepareStatement("update estoque_base set qt_Dotnet = ? , dt_data_entrada = ?");
                        
                        ps.setInt(1, qtApostilasUpdate);         
                       ps.setString(2,SysLivros.DataPTtoENtoPT(data));              //ajustar    
                                        
                        ps.execute();
                        PreparedStatement ps_InsertHistorico=Conexao.ConexaoJDBC.prepareStatement("insert into historico_base values(?,?,?,?)");
                         ps_InsertHistorico.setString(1, null);
                         ps_InsertHistorico.setString(2, curso);
                        ps_InsertHistorico.setInt(3, qtdApostila);
                        try {
                        ps_InsertHistorico.setString(4, SysLivros.DataPTtoENtoPT(data));//erro
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(this,"Erro ao cadastrar data no historico do curso 3 " +ex.getMessage());
                    }
                        ps_InsertHistorico.execute();
                      
                        JOptionPane.showMessageDialog(this, "Autualizado com sucesso", "Entrega", JOptionPane.INFORMATION_MESSAGE);
                        new Principal().setVisible(true);
                        this.dispose();}
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "Erro ao inserir dados!"+ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
                    }
                    break;
                    
                case "Java":
                    try {
                        PreparedStatement p = Conexao.ConexaoJDBC.prepareStatement( "select * from estoque_base  where qt_Java >=0 " );
                       ResultSet rs=p.executeQuery();
        while(rs.next()){
            
           qtApostilas_Atual =rs.getInt("qt_Java");
            
       
        }qtApostilasUpdate=qtdApostila+qtApostilas_Atual;
        if(JOptionPane.showConfirmDialog(this, "Verifique os dados antes de confirmar: \n"
                + "Apostila: "+curso+"\n"
               
                +"Quantidade: "+qtdApostila+"\n"
                +"Data de Envio: "+data+"\n"
               
               ,"Confirmação",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                        PreparedStatement ps = Conexao.ConexaoJDBC.prepareStatement("update estoque_base set qt_Java = ? , dt_data_entrada = ?");
                                       
                        ps.setInt(1, qtApostilasUpdate);                  
                                          
                       ps.setString(2,SysLivros.DataPTtoENtoPT(data));                   
                                       
                        ps.execute();
                      PreparedStatement ps_InsertHistorico=Conexao.ConexaoJDBC.prepareStatement("insert into historico_base values(?,?,?,?)");
                         ps_InsertHistorico.setString(1, null);
                         ps_InsertHistorico.setString(2, curso);
                       
                        ps_InsertHistorico.setInt(3, qtdApostila);
                      
                        try {
                        ps_InsertHistorico.setString(4, SysLivros.DataPTtoENtoPT(data));
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(this,"Erro ao cadastrar data no historico do curso 3 " +ex.getMessage());
                    }
                        ps_InsertHistorico.execute();
                        JOptionPane.showMessageDialog(this, "Autualizado com sucesso", "Recebimento", JOptionPane.INFORMATION_MESSAGE);
                        new Principal().setVisible(true);
                        this.dispose();}
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "Erro ao inserir dados!"+ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
                
                }   break;
                case "Linux":
                    try {
                        PreparedStatement p = Conexao.ConexaoJDBC.prepareStatement( "select * from estoque_base  where qt_Linux >=0 " );
                       ResultSet rs=p.executeQuery();
        while(rs.next()){
            
           qtApostilas_Atual =rs.getInt("qt_Linux");
            
       
        }qtApostilasUpdate=qtdApostila+qtApostilas_Atual;
        if(JOptionPane.showConfirmDialog(this, "Verifique os dados antes de confirmar: \n"
                + "Apostila: "+curso+"\n"
               
                +"Quantidade: "+qtdApostila+"\n"
                +"Data de Envio: "+data+"\n"
               
               ,"Confirmação",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                        PreparedStatement ps = Conexao.ConexaoJDBC.prepareStatement("update estoque_base set qt_Linux = ? , dt_data_entrada = ?");
                                         
                        ps.setInt(1,qtApostilasUpdate );                  
                                        
                        ps.setString(2,SysLivros.DataPTtoENtoPT(data));                                                       
                        ps.execute();
                      PreparedStatement ps_InsertHistorico=Conexao.ConexaoJDBC.prepareStatement("insert into historico_base values(?,?,?,?)");
                         ps_InsertHistorico.setString(1, null);
                         ps_InsertHistorico.setString(2, curso);
                       
                        ps_InsertHistorico.setInt(3, qtdApostila);
                      
                        try {
                        ps_InsertHistorico.setString(4, SysLivros.DataPTtoENtoPT(data));//erro
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(this,"Erro ao cadastrar data no historico do curso 3 " +ex.getMessage());
                    }
                        ps_InsertHistorico.execute();
                        JOptionPane.showMessageDialog(this, "Autualizado com sucesso", "Entrega", JOptionPane.INFORMATION_MESSAGE);
                        new Principal().setVisible(true);
                        this.dispose();}
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "Erro ao inserir dados!"+ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
                
                }   break;
                case "Windows Server": 
                    try {
                        PreparedStatement p = Conexao.ConexaoJDBC.prepareStatement( "select * from estoque_base  where qt_WindowsServer >=0 " );
                       ResultSet rs=p.executeQuery();
        while(rs.next()){
            
           qtApostilas_Atual =rs.getInt("qt_WindowsServer");
            
       
        }qtApostilasUpdate=qtdApostila+qtApostilas_Atual;
        if(JOptionPane.showConfirmDialog(this, "Verifique os dados antes de confirmar: \n"
                + "Apostila: "+curso+"\n"
               
                +"Quantidade: "+qtdApostila+"\n"
                +"Data de Envio: "+data+"\n"
               
               ,"Confirmação",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                        PreparedStatement ps = Conexao.ConexaoJDBC.prepareStatement("update estoque_base set qt_WindowsServer = ? , dt_data_entrada = ?");
                                        
                        ps.setInt(1, qtApostilasUpdate);
                       ps.setString(2,SysLivros.DataPTtoENtoPT(data));                  
                                       
                        ps.execute();
                      PreparedStatement ps_InsertHistorico=Conexao.ConexaoJDBC.prepareStatement("insert into historico_base values(?,?,?,?)");
                         ps_InsertHistorico.setString(1, null);
                         ps_InsertHistorico.setString(2, curso);
                       
                        ps_InsertHistorico.setInt(3, qtdApostila);
                      
                   try {
                        ps_InsertHistorico.setString(4, SysLivros.DataPTtoENtoPT(data));
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(this,"Erro ao cadastrar data no historico do curso 3 " +ex.getMessage());
                    }
                        ps_InsertHistorico.execute();
                        JOptionPane.showMessageDialog(this, "Autualizado com sucesso", "Entrega", JOptionPane.INFORMATION_MESSAGE);
                        new Principal().setVisible(true);
                        this.dispose();}
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "Erro ao inserir dados!"+ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
                
                }   break;}
              
            
                    if ((txtQuantidade.getText().equals("")) || (txtQuantidade.getText().equals("0"))) {
                        JOptionPane.showMessageDialog(this, "Preencha todos os campos \"Quantidade\"", "Erro", JOptionPane.ERROR_MESSAGE);
                        lblQuantidade.setForeground(Color.red);
                    } else {
                        lblQuantidade.setForeground(Color.black);
                    }
                    if (txtDataEntrada.getText().equals("  /  /    ")) {
                        JOptionPane.showMessageDialog(this, "Preencha todos os campos \"Data de entrada \"", "Erro", JOptionPane.ERROR_MESSAGE);
                        lblDataEntrada.setForeground(Color.red);
                    } else {
                        lblDataEntrada.setForeground(Color.black);
                    }
                    
            }

    }//GEN-LAST:event_btnAdicionarActionPerformed

    private void btnAdicionarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnAdicionarKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            btnAdicionarActionPerformed(null);
        }
    }//GEN-LAST:event_btnAdicionarKeyPressed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened

         
        
         
    }//GEN-LAST:event_formWindowOpened

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
 try{
        Conexao.desconectar();
        System.out.println("Desconectado!");
}catch(Exception ex){
JOptionPane.showMessageDialog(this,"Erro ao desconectar o banco"+ ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
} 
    }//GEN-LAST:event_formWindowClosed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
       
    }//GEN-LAST:event_formWindowClosing

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ReceberApostila.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ReceberApostila.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ReceberApostila.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ReceberApostila.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new ReceberApostila().setVisible(true);
                } catch (SQLException ex) {
                    Logger.getLogger(ReceberApostila.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdicionar;
    private javax.swing.JButton btnVoltar;
    private javax.swing.JComboBox cbApostila;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblApostila;
    private javax.swing.JLabel lblDataEntrada;
    private javax.swing.JLabel lblQuantidade;
    private javax.swing.JFormattedTextField txtDataEntrada;
    private javax.swing.JTextField txtQuantidade;
    // End of variables declaration//GEN-END:variables
}
